//
//  YSPPlaceholderView.swift
//  Weibo Demo
//
//  Created by 朴裕识 on 15/12/28.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class YSPPlaceholderView: UITextView {
    
    var placeholderText: String? {
        didSet {
            placeholderLabel.text = placeholderText
            placeholderLabel.sizeToFit()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
//        backgroundColor = UIColor.Color()
        prepareUI()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChanged", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func textDidChanged() {
        placeholderLabel.hidden = hasText()
    }
    
    private func prepareUI() {
        // 添加子控件
        self.addSubview(placeholderLabel)
        
        // 添加约束,如果这个Label想给其他工程使用,最好少依赖第三方框架
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        // 顶部和父控件顶部重合,有偏移
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
        // 左边和父控件的左边重合,有偏移
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))

    }

    //MARK: - 懒加载
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(18)
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
}
